/*
 * MainFrame.java
 *
 * Created on Nov 20, 2009, 8:56:31 AM
 *
 * Description:
 *      Cutthroat Caverns Toolbox
 *
 * Current Modules:
 *      Initiative Dealer and tracker
 *      Player death tracker
 *
 * Future Modules:
 *      Player health and prestige tracking
 *      Monster database and health tracking
 *
 */

package gui;

import initiative.Dealer;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import main.Main;
import player.Player;

/**
 *
 * @author dkimnach
 */
public class MainFrame extends javax.swing.JFrame {

    Main driver;
    Dealer d;

    GridBagConstraints lblLayout = new GridBagConstraints();
    GridBagConstraints txtLayout = new GridBagConstraints();

    private boolean dealt = false; // check if dealt before
    private JMenuItem miKill;
    private JMenu menuPlanB;
    private javax.swing.JDialog aboutBox;

    public MainFrame(Main driver) {
        this.driver = driver;
        init();
        initComponents();
        prepend();
    }

    public void init() {
        // init grid layouts for both labels and textboxes
        lblLayout.gridx = 0;
        lblLayout.gridy = GridBagConstraints.RELATIVE;
        lblLayout.fill = java.awt.GridBagConstraints.BOTH;
        lblLayout.insets = new java.awt.Insets(5, 5, 5, 5);

        txtLayout.gridx = 1;
        txtLayout.gridy = GridBagConstraints.RELATIVE;
        txtLayout.fill = java.awt.GridBagConstraints.BOTH;
        txtLayout.insets = new java.awt.Insets(5, 5, 5, 5);
        txtLayout.weightx = 1;
        txtLayout.weighty = 1;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        popPlayer = new javax.swing.JPopupMenu();
        miRemove = new javax.swing.JMenuItem();
        miChange = new javax.swing.JMenuItem();
        pnlMain = new javax.swing.JPanel();
        lblInit1 = new javax.swing.JLabel();
        txtName1 = new javax.swing.JTextField();
        lblInit2 = new javax.swing.JLabel();
        txtName2 = new javax.swing.JTextField();
        lblInit3 = new javax.swing.JLabel();
        txtName3 = new javax.swing.JTextField();
        lblInit4 = new javax.swing.JLabel();
        txtName4 = new javax.swing.JTextField();
        lblInit5 = new javax.swing.JLabel();
        txtName5 = new javax.swing.JTextField();
        lblInit6 = new javax.swing.JLabel();
        txtName6 = new javax.swing.JTextField();
        menuMain = new javax.swing.JMenuBar();
        menuFile = new javax.swing.JMenu();
        miExit = new javax.swing.JMenuItem();
        menuGame = new javax.swing.JMenu();
        miAdd = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        miDeal = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        miNew = new javax.swing.JMenuItem();
        menuHelp = new javax.swing.JMenu();
        miAbout = new javax.swing.JMenuItem();

        popPlayer.setLabel("");
        popPlayer.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                popPlayerPopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                popPlayerPopupMenuWillBecomeVisible(evt);
            }
        });

        miRemove.setText("Remove Player");
        miRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miRemoveActionPerformed(evt);
            }
        });
        popPlayer.add(miRemove);

        miChange.setText("Rename Player");
        miChange.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miChangeActionPerformed(evt);
            }
        });
        popPlayer.add(miChange);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowStateListener(new java.awt.event.WindowStateListener() {
            public void windowStateChanged(java.awt.event.WindowEvent evt) {
                formWindowStateChanged(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        pnlMain.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        pnlMain.setLayout(new java.awt.GridBagLayout());

        lblInit1.setFont(lblInit1.getFont().deriveFont(lblInit1.getFont().getSize()+24f));
        lblInit1.setText("1:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(lblInit1, gridBagConstraints);

        txtName1.setBackground(java.awt.Color.red);
        txtName1.setEditable(false);
        txtName1.setFont(txtName1.getFont().deriveFont(txtName1.getFont().getSize()+24f));
        txtName1.setForeground(java.awt.Color.black);
        txtName1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        txtName1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPlayerMouseClicked(evt);
            }
        });
        txtName1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPlayerFocusLost(evt);
            }
        });
        txtName1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPlayerKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(txtName1, gridBagConstraints);
        txtName1.getAccessibleContext().setAccessibleName("txtName1");

        lblInit2.setFont(new java.awt.Font("DejaVu Sans", 0, 36));
        lblInit2.setText("2:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(lblInit2, gridBagConstraints);

        txtName2.setBackground(java.awt.Color.yellow);
        txtName2.setEditable(false);
        txtName2.setFont(txtName2.getFont().deriveFont(txtName2.getFont().getSize()+24f));
        txtName2.setForeground(java.awt.Color.black);
        txtName2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        txtName2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPlayerMouseClicked(evt);
            }
        });
        txtName2.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPlayerFocusLost(evt);
            }
        });
        txtName2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPlayerKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(txtName2, gridBagConstraints);
        txtName2.getAccessibleContext().setAccessibleName("txtName2");

        lblInit3.setFont(new java.awt.Font("DejaVu Sans", 0, 36));
        lblInit3.setText("3:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(lblInit3, gridBagConstraints);

        txtName3.setBackground(new java.awt.Color(0, 51, 255));
        txtName3.setEditable(false);
        txtName3.setFont(txtName3.getFont().deriveFont(txtName3.getFont().getSize()+24f));
        txtName3.setForeground(java.awt.Color.black);
        txtName3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        txtName3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPlayerMouseClicked(evt);
            }
        });
        txtName3.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPlayerFocusLost(evt);
            }
        });
        txtName3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPlayerKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(txtName3, gridBagConstraints);
        txtName3.getAccessibleContext().setAccessibleName("txtName3");

        lblInit4.setFont(new java.awt.Font("DejaVu Sans", 0, 36));
        lblInit4.setText("4:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(lblInit4, gridBagConstraints);

        txtName4.setBackground(java.awt.Color.green);
        txtName4.setEditable(false);
        txtName4.setFont(txtName4.getFont().deriveFont(txtName4.getFont().getSize()+24f));
        txtName4.setForeground(java.awt.Color.black);
        txtName4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        txtName4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPlayerMouseClicked(evt);
            }
        });
        txtName4.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPlayerFocusLost(evt);
            }
        });
        txtName4.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPlayerKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(txtName4, gridBagConstraints);
        txtName4.getAccessibleContext().setAccessibleName("txtName4");

        lblInit5.setFont(new java.awt.Font("DejaVu Sans", 0, 36));
        lblInit5.setText("5:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(lblInit5, gridBagConstraints);

        txtName5.setBackground(java.awt.Color.magenta);
        txtName5.setEditable(false);
        txtName5.setFont(txtName5.getFont().deriveFont(txtName5.getFont().getSize()+24f));
        txtName5.setForeground(java.awt.Color.black);
        txtName5.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        txtName5.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPlayerMouseClicked(evt);
            }
        });
        txtName5.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPlayerFocusLost(evt);
            }
        });
        txtName5.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPlayerKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(txtName5, gridBagConstraints);
        txtName5.getAccessibleContext().setAccessibleName("txtName5");

        lblInit6.setFont(new java.awt.Font("DejaVu Sans", 0, 36));
        lblInit6.setText("6:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(lblInit6, gridBagConstraints);

        txtName6.setBackground(java.awt.Color.orange);
        txtName6.setEditable(false);
        txtName6.setFont(txtName6.getFont().deriveFont(txtName6.getFont().getSize()+24f));
        txtName6.setForeground(java.awt.Color.black);
        txtName6.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        txtName6.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPlayerMouseClicked(evt);
            }
        });
        txtName6.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPlayerFocusLost(evt);
            }
        });
        txtName6.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPlayerKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlMain.add(txtName6, gridBagConstraints);

        menuFile.setText("File");

        miExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
        miExit.setText("Exit");
        miExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miExitActionPerformed(evt);
            }
        });
        menuFile.add(miExit);

        menuMain.add(menuFile);

        menuGame.setText("Game");

        miAdd.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.ALT_MASK));
        miAdd.setText("Add Player");
        miAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miAddActionPerformed(evt);
            }
        });
        menuGame.add(miAdd);
        menuGame.add(jSeparator1);

        miDeal.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_SPACE, 0));
        miDeal.setText("Deal");
        miDeal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miDealActionPerformed(evt);
            }
        });
        menuGame.add(miDeal);
        menuGame.add(jSeparator2);

        miNew.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.ALT_MASK));
        miNew.setText("New");
        miNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miNewActionPerformed(evt);
            }
        });
        menuGame.add(miNew);

        menuMain.add(menuGame);

        menuHelp.setText("Help");

        miAbout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK));
        miAbout.setText("About...");
        miAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miAboutActionPerformed(evt);
            }
        });
        menuHelp.add(miAbout);

        menuMain.add(menuHelp);

        setJMenuBar(menuMain);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlMain, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlMain, javax.swing.GroupLayout.DEFAULT_SIZE, 472, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void popPlayerPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_popPlayerPopupMenuWillBecomeVisible
        try {
            JTextField field = ((JTextField) ((JPopupMenu) evt.getSource()).getInvoker());
            int to = 0;
            int from = 0;

            if (field.equals(txtName1)) {
                from = 0;

            } else if (field.equals(txtName2)) {
                from = 1;

            } else if (field.equals(txtName3)) {
                from = 2;

            } else if (field.equals(txtName4)) {
                from = 3;

            } else if (field.equals(txtName5)) {
                from = 4;

            } else if (field.equals(txtName6)) {
                from = 5;

            } else {
                showDiag("Congratulations, you have clicked a non-existant button for this context menu. \nEmail me at dkimnach@gmail.com and tell me how you did it");
            }

            if (dealt) {
                initContextMenu(field, from, to);
            } else {
                if (popPlayer.getComponentIndex(miKill) != -1) { popPlayer.remove(miKill); }
                if (popPlayer.getComponentIndex(menuPlanB) != -1) { popPlayer.remove(menuPlanB); }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            showDiag(e.toString());
        }
    }//GEN-LAST:event_popPlayerPopupMenuWillBecomeVisible

    private void txtPlayerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtPlayerMouseClicked
        JTextField field = ((JTextField)evt.getSource());
        if (!dealt) {
            setEditable(field);
        }
    }//GEN-LAST:event_txtPlayerMouseClicked

    private void txtPlayerFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPlayerFocusLost
        JTextField field = ((JTextField)evt.getSource());
        setNonEditable(field);
    }//GEN-LAST:event_txtPlayerFocusLost

    private void txtPlayerKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPlayerKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER || evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            JTextField field = ((JTextField)evt.getSource());
            setNonEditable(field);
        }
    }//GEN-LAST:event_txtPlayerKeyPressed

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        System.out.println("Key pressed on form! " + KeyEvent.getKeyText(evt.getKeyCode()));
        if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
            deal();
        }
    }//GEN-LAST:event_formKeyPressed

    private void miExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miExitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_miExitActionPerformed

    private void miNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miNewActionPerformed
        String title = "Confirm New Game";
        String msg = "This will clear all names. \nAre you sure?";
        reset(title, msg);
    }//GEN-LAST:event_miNewActionPerformed

    private void popPlayerPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_popPlayerPopupMenuWillBecomeInvisible
        
    }//GEN-LAST:event_popPlayerPopupMenuWillBecomeInvisible

    private void miAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miAboutActionPerformed
        if (aboutBox == null) {
            JFrame mainFrame = this;
            aboutBox =   new AboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        aboutBox.show();
    
    }//GEN-LAST:event_miAboutActionPerformed

    private void miAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miAddActionPerformed
        if (!dealt) {
            addPlayer();
        } else {
            if (confirmDiag("Confirm Add Player", "This will reset the initiative counter. Confirm?") == JOptionPane.OK_OPTION) {
                addPlayer();
            }
        }
    }//GEN-LAST:event_miAddActionPerformed

    private void miRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miRemoveActionPerformed
        JTextField field = ((JTextField)((JPopupMenu)((JMenuItem)evt.getSource()).getParent()).getInvoker());

        if (!dealt) {
            removePlayer(field);
        } else {
            if (confirmDiag("Confirm Remove Player", "This will reset the initiative counter. Confirm?") == JOptionPane.OK_OPTION) {
                removePlayer(field);
            }
        }
    }//GEN-LAST:event_miRemoveActionPerformed

    private void miDealActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miDealActionPerformed
        deal();
    }//GEN-LAST:event_miDealActionPerformed

    private void miChangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miChangeActionPerformed
        JTextField field = ((JTextField)((JPopupMenu)((JMenuItem)evt.getSource()).getParent()).getInvoker());

        if (!dealt) {
            setEditable(field);
        } else {
            if (confirmDiag("Confirm Change Player", "This will reset the initiative counter. Confirm?") == JOptionPane.OK_OPTION) {
                setEditable(field);
            }
        }
}//GEN-LAST:event_miChangeActionPerformed

    private void formWindowStateChanged(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowStateChanged
        Font f = new Font("DejaVu Sans", Font.PLAIN, 36);

        if (this.getExtendedState() == MainFrame.MAXIMIZED_BOTH || this.getExtendedState() == MainFrame.MAXIMIZED_VERT) {

        }
}//GEN-LAST:event_formWindowStateChanged

    private void miKillActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            JTextField field = ((JTextField)((JPopupMenu)((JMenuItem)evt.getSource()).getParent()).getInvoker());

            //field.setEnabled(!field.isEnabled());

            if (field.equals(txtName1)) {
                try {
                    killPlayer(0);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (field.equals(txtName2)) {
                try {
                    killPlayer(1);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (field.equals(txtName3)) {
                try {
                    killPlayer(2);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (field.equals(txtName4)) {
                try {
                    killPlayer(3);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (field.equals(txtName5)) {
                try {
                    killPlayer(4);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (field.equals(txtName6)) {
                try {
                    killPlayer(5);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            updatePlayers();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JLabel lblInit1;
    private javax.swing.JLabel lblInit2;
    private javax.swing.JLabel lblInit3;
    private javax.swing.JLabel lblInit4;
    private javax.swing.JLabel lblInit5;
    private javax.swing.JLabel lblInit6;
    private javax.swing.JMenu menuFile;
    private javax.swing.JMenu menuGame;
    private javax.swing.JMenu menuHelp;
    private javax.swing.JMenuBar menuMain;
    private javax.swing.JMenuItem miAbout;
    private javax.swing.JMenuItem miAdd;
    private javax.swing.JMenuItem miChange;
    private javax.swing.JMenuItem miDeal;
    private javax.swing.JMenuItem miExit;
    private javax.swing.JMenuItem miNew;
    private javax.swing.JMenuItem miRemove;
    private javax.swing.JPanel pnlMain;
    private javax.swing.JPopupMenu popPlayer;
    private javax.swing.JTextField txtName1;
    private javax.swing.JTextField txtName2;
    private javax.swing.JTextField txtName3;
    private javax.swing.JTextField txtName4;
    private javax.swing.JTextField txtName5;
    private javax.swing.JTextField txtName6;
    // End of variables declaration//GEN-END:variables

    private void initContextMenu(final JTextField field, final int from, final int to) {
        // Plan 'B' menu items
        JMenuItem miP1 = new JMenuItem();
        JMenuItem miP2 = new JMenuItem();
        JMenuItem miP3 = new JMenuItem();
        JMenuItem miP4 = new JMenuItem();
        JMenuItem miP5 = new JMenuItem();
        JMenuItem miP6 = new JMenuItem();

        if (popPlayer.getComponentIndex(miKill) == -1) {
            miKill = new JMenuItem();
            miKill.setText("Kill");
            miKill.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    System.out.println("State changed");

                    miKillActionPerformed(evt);
                }

            });
            if (field.isEnabled()) {
                popPlayer.add(miKill);
            }
        } else {
            if (!field.isEnabled()){
                popPlayer.remove(miKill);
            }
        }

        if (popPlayer.getComponentIndex(menuPlanB) != -1) { popPlayer.remove(menuPlanB); }

        menuPlanB = new JMenu();
        menuPlanB.setText("Plan 'B': Switch " + field.getText() + " with...");

        if (!field.equals(txtName1)) {
            if (txtName1.isEnabled() && !txtName1.getText().isEmpty()) {
                miP1.setText("#1: " +txtName1.getText());
                miP1.addActionListener(new java.awt.event.ActionListener() {
                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        System.out.println("Name1" + from + ", " + to);
                        d.planB(from, to);
                        updatePlayers();
                        prepend();
                    }
                });
                menuPlanB.add(miP1);
            }
        }

        if (!field.equals(txtName2)) {
            if (txtName2.isEnabled() && !txtName2.getText().isEmpty()) {
                miP2.setText("#2: " +txtName2.getText());
                miP2.addActionListener(new java.awt.event.ActionListener() {
                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        System.out.println("Name2" + from + ", " + to);
                        d.planB(from, to+1);
                        updatePlayers();
                        prepend();
                    }
                });

                menuPlanB.add(miP2);
            }
        }
        if (!field.equals(txtName3)) {
            if (txtName3.isEnabled() && !txtName3.getText().isEmpty()) {
                miP3.setText("#3: " +txtName3.getText());
                miP3.addActionListener(new java.awt.event.ActionListener() {
                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        System.out.println("Name3" + from + ", " + to);
                        d.planB(from, to+2);
                        updatePlayers();
                        prepend();
                    }
                });
                menuPlanB.add(miP3);
            }
        }
        if (!field.equals(txtName4)) {
            if (txtName4.isEnabled() && !txtName4.getText().isEmpty()) {
                miP4.setText("#4: " +txtName4.getText());
                miP4.addActionListener(new java.awt.event.ActionListener() {
                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        System.out.println("Name4" + from + ", " + to);
                        d.planB(from, to+3);
                        updatePlayers();
                        prepend();
                    }
                });
                menuPlanB.add(miP4);
            }
        }
        if (!field.equals(txtName5)) {
            if (txtName5.isEnabled() && !txtName5.getText().isEmpty()) {
                miP5.setText("#5: " +txtName5.getText());
                miP5.addActionListener(new java.awt.event.ActionListener() {
                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        System.out.println("Name5" + from + ", " + to);
                        d.planB(from, to+4);
                        updatePlayers();
                        prepend();
                    }
                });
                menuPlanB.add(miP5);
            }
        }
        if (!field.equals(txtName6)) {
            if (txtName6.isEnabled() && !txtName6.getText().isEmpty()) {
                miP6.setText("#6: " + txtName6.getText());
                miP6.addActionListener(new java.awt.event.ActionListener() {
                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        System.out.println("Name6" + from + ", " + to);
                        d.planB(from, to+5);
                        updatePlayers();
                        prepend();
                    }
                });
                menuPlanB.add(miP6);
            }
        }
        if (field.isEnabled()) {
            popPlayer.add(menuPlanB);
        }
    }

    private void showDiag(String msg) {
        JOptionPane.showMessageDialog(this, msg);
    }

    private int confirmDiag(String title, String msg) {
        return JOptionPane.showConfirmDialog(this, msg, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
    }

    private void setEditable(JTextField field) {
        field.setEditable(true);
        field.requestFocus();
        field.selectAll();
        prepend();
        dealt = false;
    }

    private void setNonEditable(JTextField field) {
        field.setEditable(false);
        if (!field.getText().isEmpty()) {
            field.setComponentPopupMenu(popPlayer);
        } else {
            field.setComponentPopupMenu(null);
        }
        prepend();
        //dealt = false;
    }

    private void prepend() {
        int init = 1;
        if (txtName1.getText().isEmpty()) {
            if (dealt) { lblInit1.setVisible(false); }
            else { 
                lblInit1.setVisible(true);
                lblInit1.setText("");
            }
        } else {
            lblInit1.setText(init + ": ");
            init++;
            lblInit1.setVisible(true);
        }

        if (txtName2.getText().isEmpty()) {
            if (dealt) { lblInit2.setVisible(false); }
            else {
                lblInit2.setVisible(true);
                lblInit2.setText("");
            }
        } else {
            lblInit2.setText(init + ": ");
            init++;
            lblInit2.setVisible(true);
        }

        if (txtName3.getText().isEmpty()) {
            if (dealt) { lblInit3.setVisible(false); }
            else {
                lblInit3.setVisible(true);
                lblInit3.setText("");
            }
        } else {
            lblInit3.setText(init + ": ");
            init++;
            lblInit3.setVisible(true);
        }

        if (txtName4.getText().isEmpty()) {
            if (dealt) { lblInit4.setVisible(false); }
            else {
                lblInit4.setVisible(true);
                lblInit4.setText("");
            }
        } else {
            lblInit4.setText(init + ": ");
            init++;
            lblInit4.setVisible(true);
        }

        if (txtName5.getText().isEmpty()) {
            if (dealt) { lblInit5.setVisible(false); }
            else {
                lblInit5.setVisible(true);
                lblInit5.setText("");
            }
        } else {
            lblInit5.setText(init + ": ");
            init++;
            lblInit5.setVisible(true);
        }

        if (txtName6.getText().isEmpty()) {
            if (dealt) { lblInit6.setVisible(false); }
            else {
                lblInit6.setVisible(true);
                lblInit6.setText("");
            }
        } else {
            lblInit6.setText(init + ": ");
            init++;
            lblInit6.setVisible(true);
        }
        validate();
    }

    public void swap(JTextField one, JTextField two) {
        Color col = one.getBackground();
        String name = one.getText();
        one.setBackground(two.getBackground());
        one.setText(two.getText());
        two.setBackground(col);
        two.setText(name);
        System.out.println("switched fields: " + one.getText() + ", " + two.getText());
        updatePlayers();
    }

    private void deal() {
        try {
            System.out.println(dealt);
            if (!dealt) { // new game/new players
                createDeck();
            } 

            // get new positions
            d.deal();
            updatePlayers();
        } catch (Exception e) {
            //e.printStackTrace();
            // do nothing - trying to deal with no names
        }
    }

    private void createDeck() {
        ArrayList<Player> players = new ArrayList<Player>();
        
        if (!txtName1.getText().isEmpty()) {
            Player p = new Player(txtName1.getText(), txtName1.getBackground());
            if (!txtName1.isEnabled()) { p.die(); }
            players.add(p);
        }

        if (!txtName2.getText().isEmpty()) {
            Player p = new Player(txtName2.getText(), txtName2.getBackground());
            if (!txtName2.isEnabled()) { p.die(); }
            players.add(p);
        }

        if (!txtName3.getText().isEmpty()) {
            Player p = new Player(txtName3.getText(), txtName3.getBackground());
            if (!txtName3.isEnabled()) { p.die(); }
            players.add(p);
        } 

        if (!txtName4.getText().isEmpty()) {
            Player p = new Player(txtName4.getText(), txtName4.getBackground());
            if (!txtName4.isEnabled()) { p.die(); }
            players.add(p);
        } 

        if (!txtName5.getText().isEmpty()) {
            Player p = new Player(txtName5.getText(), txtName5.getBackground());
            if (!txtName5.isEnabled()) { p.die(); }
            players.add(p);
        } 

        if (!txtName6.getText().isEmpty()) {
            Player p = new Player(txtName6.getText(), txtName6.getBackground());
            if (!txtName6.isEnabled()) { p.die(); }
            players.add(p);
        }

        txtName1.setText(null);
        txtName2.setText(null);
        txtName3.setText(null);
        txtName4.setText(null);
        txtName5.setText(null);
        txtName6.setText(null);

        players.trimToSize();
        setDeck(players);
        dealt = true;
    }

    private void killPlayer(int i) throws Exception {
        d.killPlayer(i);
        updatePlayers();
    }

    public void setDeck(ArrayList<Player> p) {
        System.out.println("New deck set");
        d = new Dealer(p);
    }

    private void updatePlayers() {

        ArrayList<Player> players = d.getList();
        
        if (players.size() > 5) { // 6 players
            txtName6.setText(players.get(5).getName());
            txtName6.setBackground(players.get(5).getColor());
            txtName6.setEnabled(!players.get(5).isDead());
            txtName6.setVisible(true);
        } else {
            txtName6.setVisible(false);
        }

        if (players.size() > 4) { // 5 players
            txtName5.setText(players.get(4).getName());
            txtName5.setBackground(players.get(4).getColor());
            txtName5.setEnabled(!players.get(4).isDead());
            txtName5.setVisible(true);
        } else {
            txtName5.setVisible(false);
        }

        if (players.size() > 3) { // 4 players
            txtName4.setText(players.get(3).getName());
            txtName4.setBackground(players.get(3).getColor());
            txtName4.setEnabled(!players.get(3).isDead());
            txtName4.setVisible(true);
        } else {
            txtName4.setVisible(false);
        }

        if (players.size() > 2) {
            txtName3.setText(players.get(2).getName());
            txtName3.setBackground(players.get(2).getColor());
            txtName3.setEnabled(!players.get(2).isDead());
            txtName3.setVisible(true);
        } else {
            txtName3.setVisible(false);
        }

        if (players.size() > 1) {
            txtName2.setText(players.get(1).getName());
            txtName2.setBackground(players.get(1).getColor());
            txtName2.setEnabled(!players.get(1).isDead());
            txtName2.setVisible(true);
        } else {
            txtName2.setVisible(false);
        }

        if (players.size() > 0) {
            txtName1.setText(players.get(0).getName());
            txtName1.setBackground(players.get(0).getColor());
            txtName1.setEnabled(!players.get(0).isDead());
            txtName1.setVisible(true);
        } else {
            txtName1.setVisible(false);
        }

        this.setTitle("Initiative: " + d.getCounter());
        validate();
        setFont();
    }

    private void reset(String title, String msg) {
        if (confirmDiag(title, msg) == JOptionPane.OK_OPTION) {
            dealt = false;
            this.setTitle(null);

            txtName1.setText(null);
            txtName1.setEnabled(true);
            txtName1.setBackground(Color.red);

            txtName2.setText(null);
            txtName2.setEnabled(true);
            txtName2.setBackground(Color.yellow);

            txtName3.setText(null);
            txtName3.setEnabled(true);
            txtName3.setBackground(Color.blue);

            txtName4.setText(null);
            txtName4.setEnabled(true);
            txtName4.setBackground(Color.green);

            txtName5.setText(null);
            txtName5.setEnabled(true);
            txtName5.setBackground(Color.magenta);

            txtName6.setText(null);
            txtName6.setEnabled(true);
            txtName6.setBackground(Color.orange);

            prepend();
            setFont();
        }
    }

    private void addPlayer() {
        if (!txtName1.isVisible()) { txtName1.setVisible(true); }
        else if (!txtName2.isVisible()) {txtName2.setVisible(true); }
        else if (!txtName3.isVisible()) {txtName3.setVisible(true); }
        else if (!txtName4.isVisible()) {txtName4.setVisible(true); }
        else if (!txtName5.isVisible()) {txtName5.setVisible(true); }
        else if (!txtName6.isVisible()) {txtName6.setVisible(true); }
        else {
            showDiag("Can only add up to 6 players");
        }

        dealt = false;
        prepend();
        
    }

    private void removePlayer(JTextField field) {
        field.setText(null);
        field.setVisible(false);
        dealt = false;
        prepend();
        
    }

    private void setFont() {
        System.out.println("sizing font...");
        int size = Math.round(txtName1.getHeight() / 2);
        Font f = new Font("DejaVu Sans", Font.PLAIN, size);

        lblInit1.setFont(f);
        lblInit2.setFont(f);
        lblInit3.setFont(f);
        lblInit4.setFont(f);
        lblInit5.setFont(f);
        lblInit6.setFont(f);

        txtName1.setFont(f);
        txtName2.setFont(f);
        txtName3.setFont(f);
        txtName4.setFont(f);
        txtName5.setFont(f);
        txtName6.setFont(f);

        validate();
    }
}